package com.jh3502.vivo.function.tododetail.travel;

import android.graphics.Color;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jh3502.vivo.R;
import com.jh3502.vivo.base.BaseActivity;
import com.jh3502.vivo.function.citylist.CityBean;
import com.jh3502.vivo.function.contact.ContactBean;
import com.jh3502.vivo.function.contact.ContactDetailActivity;
import com.jh3502.vivo.function.dialog.TouchImageView;
import com.jh3502.vivo.function.todo.TodoListBean;
import com.jh3502.vivo.function.travelnew.PhotoChosenAdapter;
import com.jh3502.vivo.function.travelnew.TravelNewActivity;
import com.jh3502.vivo.function.travelnew.TravelNewBean;
import com.jh3502.vivo.net.ApiConstants;
import com.jh3502.vivo.utils.Constant;
import com.jh3502.vivo.utils.Utils;
import com.jh3502.vivo.view.MyRecyclerView;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * author:harisucici on 2018/11/7 10:42
 * email:harisucici@gmail.com
 * name:
 * todo:
 */
public class TodoTravelActivity extends BaseActivity<TodoTravelPresenter.TodoDetailView, TodoTravelPresenter> implements TodoTravelPresenter.TodoDetailView {

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.todo_detail_recycler)
    MyRecyclerView todoDetailRecycler;
    @BindView(R.id.todo_detail_travel_iv1)
    ImageView todoDetailTravelIv1;
    @BindView(R.id.todo_detail_travel_msg)
    ConstraintLayout todoDetailTravelMsg;
    @BindView(R.id.todo_detail_travel_iv2)
    ImageView todoDetailTravelIv2;
    @BindView(R.id.todo_detail_travel_change)
    ConstraintLayout todoDetailTravelChange;
    @BindView(R.id.include_todo_detail_travel_msg)
    View includeTodoDetailTravelMsg;
    @BindView(R.id.include_todo_detail_travel_change)
    View includeTodoDetailTravelChange;
    @BindView(R.id.todo_detail_photo)
    MyRecyclerView todoDetailPhoto;
    @BindView(R.id.todo_detail_travel_name)
    TextView todoDetailTravelName;
    @BindView(R.id.todo_detail_travel_point)
    ImageView todoDetailTravelPoint;
    @BindView(R.id.todo_detail_travel_status)
    TextView todoDetailTravelStatus;
    @BindView(R.id.todo_detail_travel_num)
    TextView todoDetailTravelNum;
    @BindView(R.id.todo_detail_travel_date)
    TextView todoDetailTravelDate;
    @BindView(R.id.todo_detail_travel_dep)
    TextView todoDetailTravelDep;
    @BindView(R.id.travel_new_photo_add)
    ImageView travelNewPhotoAdd;
    @BindView(R.id.todo_detail_travel_change_recycle)
    MyRecyclerView todoDetailTravelChangeRecycle;
    @BindView(R.id.todo_detail_approve_delete)
    TextView todoDetailApproveDelete;
    @BindView(R.id.todo_detail_reject)
    TextView todoDetailReject;
    @BindView(R.id.todo_detail_submit)
    TextView todoDetailSubmit;
    @BindView(R.id.lapprove)
    LinearLayout lapprove;
    @BindView(R.id.todo_detail_delete)
    TextView todoDetailDelete;
    @BindView(R.id.todo_detail_change)
    TextView todoDetailChange;
    @BindView(R.id.lstart)
    LinearLayout lstart;
    private List<String> pics = new ArrayList<>(2);

    private TodoTravelAdapter mAdapter;
    private PhotoChosenAdapter photoChosenAdapter;
    private int userId;
    private TodoDetailChangeAdapter todoDetailChangeAdapter;
    private String name;
    private TodoListBean todoListBean;
    private List<Map<String, Object>> bodyList = new ArrayList<>(2);
    private List<String> contains = new ArrayList<>(2);
    private List<Map<String, Object>> listItems = new ArrayList<>(2);


    @Override
    public TodoTravelPresenter initPresenter() {
        return new TodoTravelPresenter();
    }

    @Override
    protected int setViewId() {
        return R.layout.activity_todo_detail_travel;
    }

    @Override
    protected void initView() {
        toolbar.setTitle("");
        toolbarTitle.setText("待办");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mPresenter.setTodoDetailView(this);

        todoDetailRecycler.setNestedScrollingEnabled(false);
        mAdapter = new TodoTravelAdapter(this, listItems);
        todoDetailRecycler.setAdapter(mAdapter);


        StaggeredGridLayoutManager staggeredGridLayoutManager =
                new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        photoChosenAdapter = new PhotoChosenAdapter(this, pics);
        photoChosenAdapter.setShowDelete(false);
        photoChosenAdapter.setOnItemClickListener(s -> {
            Bundle bundle = new Bundle();
            bundle.putString("url", ApiConstants.getApiHost() + pics.get(s));
            Utils.getInstance().startActivity(TodoTravelActivity.this, TouchImageView.class, bundle);
        });

        todoDetailPhoto.setLayoutManager(staggeredGridLayoutManager);
        todoDetailPhoto.setAdapter(photoChosenAdapter);

        Map<String, Object> body = new HashMap<>(2);
        body.put("id", getIntent().getExtras().getInt("id"));
        mPresenter.toGetTravelById(body);

        Map<String, Object> bodyChange = new HashMap<>(2);
        bodyChange.put("businessNo", getIntent().getExtras().getString("businessNo"));
        mPresenter.toGetChangeAndAuditRecords(bodyChange);


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
            default:
        }
        return true;
    }

    @Override
    protected void initData() {
        if (!TextUtils.isEmpty(getIntent().getExtras().getString("bean"))) {
            todoListBean = new Gson().fromJson(getIntent().getExtras().getString("bean"),
                    TodoListBean.class);
        }

    }

    @Override
    protected void doOnDestroy() {

    }

    @Override
    protected void doOnResume() {

    }

    @Override
    protected void doOnSaveInstanceState(Bundle savedInstanceState) {

    }

    @Override
    public void responseError(int code, String msg) {

    }

    @Override
    public void getTravelByIdSuccess(TravelNewBean travelNewBean) {
        StringBuffer sbTitle = new StringBuffer();
        userId = travelNewBean.getUserId();
        name = travelNewBean.getName();
        sbTitle.append(name);
        sbTitle.append("的出差审批");

        int state = travelNewBean.getState();
        int source = getIntent().getIntExtra("source", -1);

        if (state == 0) {
            Glide.with(this).load(R.drawable.point_red).into(todoDetailTravelPoint);
            todoDetailTravelStatus.setText("待审批");
            todoDetailTravelStatus.setTextColor(Color.parseColor("#FFF36C60"));
            if (source == Constant.TRAVEL_START) {
                lstart.setVisibility(View.VISIBLE);
                lapprove.setVisibility(View.GONE);
            } else {
                lstart.setVisibility(View.GONE);
                lapprove.setVisibility(View.VISIBLE);
            }
            lstart.setVisibility(View.GONE);
            todoDetailApproveDelete.setVisibility(View.GONE);
            todoDetailReject.setVisibility(View.VISIBLE);
            todoDetailSubmit.setVisibility(View.VISIBLE);


        } else if (state == 1) {
            Glide.with(this).load(R.drawable.point_green).into(todoDetailTravelPoint);
            todoDetailTravelStatus.setText("已批准");
            todoDetailTravelStatus.setTextColor(Color.parseColor("#FF0EC053"));
            if (source == Constant.TRAVEL_START) {
                lstart.setVisibility(View.VISIBLE);
                lapprove.setVisibility(View.GONE);
            } else {
                lstart.setVisibility(View.GONE);
                lapprove.setVisibility(View.VISIBLE);
            }
            lstart.setVisibility(View.VISIBLE);

            todoDetailApproveDelete.setVisibility(View.VISIBLE);
            todoDetailReject.setVisibility(View.GONE);
            todoDetailSubmit.setVisibility(View.GONE);
        } else if (state == 2) {
            Glide.with(this).load(R.drawable.point_blue).into(todoDetailTravelPoint);
            todoDetailTravelStatus.setText("审批被拒绝");
            todoDetailTravelStatus.setTextColor(Color.parseColor("#FF3389FF"));
            if (source == Constant.TRAVEL_START) {
                lstart.setVisibility(View.VISIBLE);
                lapprove.setVisibility(View.GONE);
            } else {
                lstart.setVisibility(View.GONE);
                lapprove.setVisibility(View.VISIBLE);
            }
            lstart.setVisibility(View.VISIBLE);
            todoDetailApproveDelete.setVisibility(View.VISIBLE);
            todoDetailReject.setVisibility(View.GONE);
            todoDetailSubmit.setVisibility(View.GONE);
        }


        todoDetailTravelNum.setText(travelNewBean.getBusinessNo());
        todoDetailTravelDate.setText(travelNewBean.getCreateDate());
        todoDetailTravelDep.setText(travelNewBean.getDeptName());

        todoDetailTravelName.setText(sbTitle.toString());
        contains.add(travelNewBean.getBusinesstrip());
        contains.add(travelNewBean.getStartdate());
        contains.add(travelNewBean.getEnddate());
        Date date1 = Utils.getInstance().string2Date(travelNewBean.getStartdate());
        Date date2 = Utils.getInstance().string2Date(travelNewBean.getEnddate());
        contains.add(Utils.getInstance().getDateCount(date1, date2) + "天");

        List<CityBean> list = new Gson().fromJson(travelNewBean.getDestination(),
                new TypeToken<List<CityBean>>() {
                }.getType());
        StringBuffer stringBufferCity = new StringBuffer();
        for (CityBean cityBean : list) {
            stringBufferCity.append(cityBean.getName());
            stringBufferCity.append("、");
        }
        contains.add(stringBufferCity.toString().substring(0, stringBufferCity.toString().length() - 1));

        List<ContactBean> personsChosen = new Gson().fromJson(travelNewBean.getPerson(),
                new TypeToken<List<ContactBean>>() {
                }.getType());
        StringBuffer stringBuffer = new StringBuffer();
        for (ContactBean contactBean : personsChosen) {
            stringBuffer.append(contactBean.getName());
            stringBuffer.append("、");

        }
        contains.add(
                stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1));


        int isdriver = travelNewBean.getIsdriver();
        if (isdriver == 1) {
            contains.add("是");

        } else {
            contains.add("否");
        }
        contains.add(travelNewBean.getOvertop() + "");
        contains.add(travelNewBean.getReason());
        String[] titles = getResources().getStringArray(R.array.titles);
        for (int i = 0; i < titles.length; i++) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("title", titles[i]);
            map.put("contain", contains.get(i));
            listItems.add(map);

        }
        mAdapter.notifyDataSetChanged();
        pics.addAll(Utils.getInstance().jsa2listString(travelNewBean.getEnclosure()));
        photoChosenAdapter.notifyDataSetChanged();
    }

    @Override
    public void getUserSuccess(Map<String, Object> map) {
        Bundle bundle = new Bundle();
        bundle.putString("name", (String) map.get("username"));
        bundle.putString("postname", (String) map.get("postName"));
        bundle.putString("telephone", (String) map.get("telephone"));
        bundle.putString("mobile", (String) map.get("mobile"));
        Utils.getInstance().startActivity(this, ContactDetailActivity.class, bundle);
    }

    @Override
    public void getChangeAndAuditRecordsSuccess(List<TodoDetailChangeBean> beans) {

        todoDetailTravelChangeRecycle.setNestedScrollingEnabled(false);
        todoDetailChangeAdapter = new TodoDetailChangeAdapter(this, beans);
        todoDetailChangeAdapter.setName(name);
        todoDetailTravelChangeRecycle.setAdapter(todoDetailChangeAdapter);
    }

    @Override
    public void agreeForAllSuccess() {
        showShortToast("操作成功");
        onBackPressed();
    }

    @Override
    public void deleteAuditSuccess() {
        showShortToast("删除成功");
        onBackPressed();
    }

    @Override
    public void deleteTaskSuccess() {
        showShortToast("删除成功");
        onBackPressed();
    }


    @OnClick(R.id.todo_detail_travel_msg)
    public void onTodoDetailTravelMsgClicked() {
        if (includeTodoDetailTravelMsg.getVisibility() == View.GONE) {
            todoDetailTravelMsg.setBackgroundColor(Color.parseColor("#FFE2E7E9"));
            Glide.with(this).load(R.drawable.ic_expand_less_black_24dp).into(todoDetailTravelIv1);
            includeTodoDetailTravelMsg.setVisibility(View.VISIBLE);
        } else {
            todoDetailTravelMsg.setBackgroundColor(Color.WHITE);
            Glide.with(this).load(R.drawable.ic_expand_more_black_24dp).into(todoDetailTravelIv1);
            includeTodoDetailTravelMsg.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.todo_detail_travel_change)
    public void onTodoDetailTravelChangeClicked() {
        if (includeTodoDetailTravelChange.getVisibility() == View.GONE) {
            todoDetailTravelChange.setBackgroundColor(Color.parseColor("#FFE2E7E9"));
            Glide.with(this).load(R.drawable.ic_expand_less_black_24dp).into(todoDetailTravelIv2);
            includeTodoDetailTravelChange.setVisibility(View.VISIBLE);
        } else {
            todoDetailTravelChange.setBackgroundColor(Color.WHITE);
            Glide.with(this).load(R.drawable.ic_expand_more_black_24dp).into(todoDetailTravelIv2);
            includeTodoDetailTravelChange.setVisibility(View.GONE);
        }
    }


    @OnClick(R.id.todo_detail_travel_person)
    public void onTodoDetailTravelPersonClicked() {
        Map<String, Object> body = new HashMap<>(2);
        body.put("userId", userId);
        mPresenter.toGetUser(body);

    }

    private Map<String, Object> doApprove(int state, TodoListBean todoListBean) {
        Map<String, Object> body = new HashMap<>(2);
        body.put("userId", todoListBean.getUserId());
        body.put("type", todoListBean.getType());
        body.put("state", state);
        body.put("destination", todoListBean.getDestination());
        body.put("businessNo", todoListBean.getBusinessNo());
        body.put("id", todoListBean.getId());
        body.put("flowNo", todoListBean.getFlowNo());
        body.put("currentNodeNo", todoListBean.getCurrentNodeNo());
        return body;
    }


    @OnClick(R.id.todo_detail_approve_delete)
    public void onTodoDetailApproveDeleteClicked() {
        Map<String, Object> body = new HashMap<>(2);
        body.put("id", todoListBean.getAuditId());
        body.put("type", Constant.TYPE_TRAVEL);
        mPresenter.toDeleteAudit(body);
    }

    @OnClick(R.id.todo_detail_reject)
    public void onTodoDetailRejectClicked() {
        bodyList.clear();
        bodyList.add(doApprove(2, todoListBean));
        mPresenter.toAgreeForAll(bodyList);
    }

    @OnClick(R.id.todo_detail_submit)
    public void onTodoDetailSubmitClicked() {
        bodyList.clear();
        bodyList.add(doApprove(1, todoListBean));
        mPresenter.toAgreeForAll(bodyList);
    }

    @OnClick(R.id.todo_detail_delete)
    public void onTodoDetailDeleteClicked() {
        Map<String, Object> body = new HashMap<>(2);
        body.put("id", getIntent().getExtras().getInt("id"));
        mPresenter.toDeleteTask(body);
    }

    @OnClick(R.id.todo_detail_change)
    public void onTodoDetailChangeClicked() {
        Bundle bundle = new Bundle();
        bundle.putInt("id", getIntent().getExtras().getInt("id"));
        Utils.getInstance().startActivity(this, TravelNewActivity.class, bundle);
    }
}
